package com.seagox.chat.chat.service.impl;

import com.seagox.chat.chat.entity.ChatContact;
import com.seagox.chat.chat.entity.ChatMessage;
import com.seagox.chat.chat.entity.ChatRoom;
import com.seagox.chat.chat.mapper.ChatContactMapper;
import com.seagox.chat.chat.mapper.ChatMessageMapper;
import com.seagox.chat.chat.mapper.ChatRoomMapper;
import com.seagox.chat.chat.service.IChatMessageService;
import com.seagox.chat.common.ResultData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 聊天消息 服务实现类
 */
@Service
public class ChatMessageService extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

	@Autowired
	private ChatMessageMapper chatMessageMapper;

	@Autowired
	private ChatContactMapper chatContactMapper;

	@Autowired
	private ChatRoomMapper chatRoomMapper;

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;

	@Override
	public ResultData queryByPage(String sessionId, String userId, String startTime, String typeStr, String content) {
		PageHelper.startPage(1, 20);
		List<String> typeList = new ArrayList<>();
		if (!StringUtils.isEmpty(typeStr)) {
			typeList = Arrays.asList(typeStr.split(","));
		}
		List<ChatMessage> list = chatMessageMapper.queryByPage(sessionId, userId, startTime, typeList, content);
		Collections.reverse(list);
		PageInfo<ChatMessage> pageInfo = new PageInfo<>(list);
		return ResultData.success(pageInfo);
	}

	@Transactional
	@Override
	public ResultData deleteByMsgid(String msgid, String userId, String sessionId) {
		LambdaQueryWrapper<ChatMessage> qw = new LambdaQueryWrapper<>();
		qw.eq(ChatMessage::getMsgid, msgid).eq(ChatMessage::getTarget, userId);
		chatMessageMapper.delete(qw);
		List<ChatMessage> list = chatMessageMapper.queryByPage(sessionId, userId, "", null, "");
		LambdaQueryWrapper<ChatContact> uw = new LambdaQueryWrapper<>();
		uw.eq(ChatContact::getSessionId, sessionId).eq(ChatContact::getMsgid, msgid).eq(ChatContact::getSource, userId);
		if (list.size() == 0) {
			ChatContact chatContact = new ChatContact();
			chatContact.setType(1);
			chatContact.setContent("");
			chatContactMapper.update(chatContact, uw);
			return ResultData.success(null);
		} else {
			ChatMessage chatMessage = list.get(0);
			ChatContact chatContact = new ChatContact();
			chatContact.setType(chatMessage.getType());
			chatContact.setContent(chatMessage.getContent());
			chatContact.setMsgid(chatMessage.getMsgid());
			chatContactMapper.update(chatContact, uw);
			return ResultData.success(chatMessage);
		}
	}

	@Transactional
	@Override
	public ResultData clear(String userId, String sessionId) {
		LambdaQueryWrapper<ChatMessage> qw = new LambdaQueryWrapper<>();
		qw.eq(ChatMessage::getSessionId, sessionId).eq(ChatMessage::getTarget, userId);
		chatMessageMapper.delete(qw);
		LambdaQueryWrapper<ChatContact> uw = new LambdaQueryWrapper<>();
		uw.eq(ChatContact::getSessionId, sessionId).eq(ChatContact::getSource, userId);
		ChatContact chatContact = new ChatContact();
		chatContact.setType(1);
		chatContact.setContent("");
		chatContactMapper.update(chatContact, uw);
		return ResultData.success(null);
	}

	@Transactional
	@Override
	public ResultData revoke(String userId, String sessionId, String msgid) {
		LambdaQueryWrapper<ChatContact> qwContact = new LambdaQueryWrapper<>();
		qwContact.eq(ChatContact::getMsgid, msgid);
		ChatContact chatContact = new ChatContact();
		chatContact.setType(0);
		chatContactMapper.update(chatContact, qwContact);
		LambdaQueryWrapper<ChatMessage> qwMessage = new LambdaQueryWrapper<>();
		qwMessage.eq(ChatMessage::getMsgid, msgid);
		ChatMessage chatMessage = new ChatMessage();
		chatMessage.setType(0);
		chatMessageMapper.update(chatMessage, qwMessage);

		ChatRoom chatRoom = chatRoomMapper.selectById(sessionId);
		List<String> target = Arrays.asList(chatRoom.getMembers().split(","));
		JSONObject message = new JSONObject();
		message.put("sessionId", sessionId);
		message.put("msgid", msgid);
		message.put("target", target);
		redisTemplate.convertAndSend("revoke", message.toJSONString());
		return ResultData.success(null);
	}

	@Override
	public ResultData queryPictureAndVideo(String sessionId, String userId, String startTime, String endTime) {
		JSONObject result = new JSONObject();
		List<ChatMessage> messageList = chatMessageMapper.queryPictureAndVideo(sessionId, userId, startTime, endTime);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		for (int i = 0; i < messageList.size(); i++) {
			ChatMessage chatMessage = messageList.get(i);
			String yearAndMonth = sdf.format(chatMessage.getCreateTime());
			if(result.containsKey(yearAndMonth)) {
				JSONArray list = result.getJSONArray(yearAndMonth);
				list.add(chatMessage);
				result.put(yearAndMonth, list);
			} else {
				JSONArray list = new JSONArray();
				list.add(chatMessage);
				result.put(yearAndMonth, list);
			}
		}
		return ResultData.success(result);
	}

}
